
#coding:utf-8
'''

@author: author
'''
from flask import request,redirect
from flask_admin.contrib.sqla.view import ModelView
from app import db,app,  login_manager
from app.admin.model import AdminUser
from flask_login import current_user,login_user,logout_user

from wtforms import form, fields, validators
from flask_admin import expose,AdminIndexView,helpers
from flask import url_for
from flask_admin.base import Admin
from wtforms.fields.core import SelectField

from app.models.model import AuthorInfo


@login_manager.user_loader
def load_user(user_id):
    return AdminUser.query.get(user_id)

class AdminModelView(ModelView):

    def is_accessible(self):
        '''是否可见权限控制
        '''
        if not current_user.is_authenticated:
            return False
        if self.model.__tablename__=="flask_admin":
            return current_user.user_type
        return current_user.is_authenticated
    
class AdminUserModelView(AdminModelView):
    
    @property
    def can_edit(self):
        '''可编辑
        '''
        return current_user.user_type
    
    @property
    def can_delete(self):
        '''可删除
        '''
        return current_user.user_type
    
    @property
    def can_create(self):
        '''可创建
        '''
        return current_user.user_type
    
    def on_model_change(self, form, user):
        # 调用用户模型中定义的set方法
        user.set_password(form.password.data)
        
    column_labels = dict(
        id=u"ID",
        username=u'帐号',
        password=u"密码",
        user_type=u"类型",
        create_time=u"创建时间"
        )
    
    form_overrides = dict(user_type=SelectField)
    
    form_args = dict(
        user_type=dict(
          choices=[("0", '普通管理'), ("1", '超级管理员')],
          validators = []
        )
    )

class LoginForm(form.Form):
    '''登录表单
    '''
    login = fields.StringField(validators=[validators.required()],label="帐号")
    password = fields.PasswordField(validators=[validators.required()],label="密码")

    def validate_login(self,_):
        '''登录验证
        '''
        user = self.get_user()
        if user is None:
            raise validators.ValidationError('用户不存在')

        if not user.check_password(self.password.data):
            raise validators.ValidationError('密码错误')

    def get_user(self):
        return AdminUser.query.filter_by(username=self.login.data).first()
    
    
class MyAdminIndexView(AdminIndexView):

    @expose('/')
    def index(self):
        if not current_user.is_authenticated:
            return redirect(url_for('.login_view'))
        return super(MyAdminIndexView, self).index()

    @expose('/login/', methods=('GET', 'POST'))
    def login_view(self):
        form = LoginForm(request.form)
        if helpers.validate_form_on_submit(form):
            user = form.get_user()
            login_user(user)
        if current_user.is_authenticated:
            return redirect(url_for('.index'))
        self._template_args['form'] = form
        return super(MyAdminIndexView, self).index()

    @expose('/logout/')
    def logout_view(self):
        logout_user()
        return redirect(url_for('.index'))

admin = Admin(app, 'ADMINX', index_view=MyAdminIndexView(), base_template='admin/master_custom.html')
admin.add_view(AdminUserModelView(AdminUser,db.session,name=u'管理员',category="管理"))
admin.add_view(AdminUserModelView(AuthorInfo,db.session,name=u'管理员',category="作者信息"))
